package com.htandroid.htandroid.aty;

import android.app.AlertDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.ab.soap.AbSoapListener;
import com.ab.soap.AbSoapParams;
import com.ab.soap.AbSoapUtil;
import com.ab.task.AbTask;
import com.ab.task.AbTaskItem;
import com.ab.task.AbTaskObjectListener;
import com.ab.util.AbDialogUtil;
import com.ab.util.AbToastUtil;
import com.ab.view.ioc.AbIocView;
import com.google.gson.Gson;
import com.htandroid.htandroid.R;
import com.htandroid.htandroid.entity.UaAccount;
import com.htandroid.htandroid.entity.UserAuth;
import com.htandroid.htandroid.global.MyApplication;
import com.htandroid.htandroid.sys.InstorageURL;
import com.htandroid.htandroid.sys.User;
import com.htandroid.htandroid.tools.MyStringUtil;
import com.htandroid.htandroid.tools.ToolSOAPxml;
import com.htandroid.htandroid.views.MySelectedDialogFragment;
import com.htandroid.htandroid.views.MySelectedDialogFragmentTime;
import com.htandroid.htandroid.webservice.BuildQgdListXMLService;
import com.htandroid.htandroid.webservice.XMLUserAuthlist;
import com.htandroid.reconstitute.base.ConstanceHeTai;
import com.htandroid.reconstitute.base.ConstanceHttp;
import com.htandroid.reconstitute.entity.CountListBean;
import com.htandroid.reconstitute.entity.UserPermissionBean;
import com.htandroid.reconstitute.http.OkHttpRequestUtils;
import com.htandroid.reconstitute.utils.SpUtil;
import com.htandroid.reconstitute.utils.ToastUtil;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;
import com.zhy.http.okhttp.request.OkHttpRequest;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;

import cn.jpush.android.api.JPushInterface;
import okhttp3.Call;

import static com.htandroid.htandroid.constance.ConstanceServer.BaseUrl_New;

/**
 * Created by lkp on 2015/11/26.
 */
public class Login_choose extends MyBaseActivity {
    private ArrayList<String> list_id = new ArrayList<>();
    private ArrayList<String> list_cacc = new ArrayList<>();
    private ArrayList<String> list_iyear = new ArrayList<>();
    private ArrayList<String> years = new ArrayList<>();
    private MyApplication application;
    private String caccStr, caccIdStr, yearStr;
    private String regId1 = "";
    private ArrayList<UserAuth> userauthlist;//用户权限
    private ArrayList<UaAccount> uaaccountlist;
    private AbSoapUtil mAbSoapUtil = null;
    private Button btn_ref;
    @AbIocView(id = R.id.ll_order, click = "oClick")
    View ll_order;
    @AbIocView(id = R.id.ll_year, click = "oClick")
    View ll_year;
    @AbIocView(id = R.id.ll_time, click = "oClick")
    View ll_time;
    @AbIocView(id = R.id.tv_order)
    TextView tv_order;
    @AbIocView(id = R.id.tv_year)
    TextView tv_year;
    @AbIocView(id = R.id.tv_time)
    TextView tv_time;
    @AbIocView(id = R.id.tv_ok, click = "oClick")
    TextView tv_ok;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setAbContentView(R.layout.layout_login_choose);
        initview();
        getDataList();
        deviceCheck(regId1);

    }



    private void getDataList() {
        String userName = SpUtil.getString(Login_choose.this, ConstanceHeTai.user_name);
        String address = SpUtil.getString(Login_choose.this, ConstanceHeTai.login_server_address);
        String url = ConstanceHttp.base_url + address + ConstanceHttp.sysabout_cacc_list;

        OkHttpUtils.post().url(url).addParams("user", userName).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                ToastUtil.showToast("服务器异常");

            }

            @Override
            public void onResponse(String response, int id) {
                try {
                    if (TextUtils.isEmpty(response)) {
                        ToastUtil.showToast("暂无数据");
                    } else {
                        Gson gson = new Gson();
                        CountListBean countListBean = gson.fromJson(response, CountListBean.class);
                        if (countListBean != null) {
                            List<CountListBean.CaccBean> cacc = countListBean.getCacc();
                            if (cacc != null) {
                                for (int i = 0; i < cacc.size(); i++) {
                                    String cacc_id = cacc.get(i).getCacc_id() == null ? "" : cacc.get(i).getCacc_id();
                                    String cacc_name = cacc.get(i).getCacc_name() == null ? "" : cacc.get(i).getCacc_name();
                                    String cacc_year = cacc.get(i).getIyears() == null ? "" : cacc.get(i).getIyears();
                                    list_id.add(cacc_id);
                                    list_cacc.add(cacc_name);
                                    list_iyear.add(cacc_year);
                                }
                                changeSlected(true);//切换显示数据
                            }
                        }

                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                    ToastUtil.showToast("数据异常");
                }

            }
        });

    }

    //界面初始化
    private void initview() {
        application = (MyApplication) abApplication;//获得我们的应用程序全局变量
        titleBar.setTitleText(R.string.select_zhangtao);
        titleBar.setLogo(R.mipmap.icon_back);
        titleBar.clearRightView();
        View rightView = mInflater.inflate(R.layout.ref_new, null);
        btn_ref = (Button) rightView.findViewById(R.id.icon_ref);
        btn_ref.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                deviceCheck(regId1);
            }
        });
        titleBar.addRightView(rightView);
        mAbSoapUtil = AbSoapUtil.getInstance(this);
        mAbSoapUtil.setTimeout(10000);

        JPushInterface.setDebugMode(true);
        JPushInterface.init(getApplicationContext());
        if (JPushInterface.isPushStopped(getApplicationContext())) {
            JPushInterface.resumePush(getApplicationContext());//恢复极光推送
        }
        regId1 = JPushInterface.getRegistrationID(this);

        caccIdStr = application.mSharedPreferences.getString("cacc_id", "");
        caccStr = application.mSharedPreferences.getString("cacc_name", "");
        yearStr = application.mSharedPreferences.getString("ciyear", "");

        if (!MyStringUtil.isEmpty(caccStr)) {
            tv_order.setText(caccStr);
        }
        if (!MyStringUtil.isEmpty(yearStr)) {
            tv_year.setText(yearStr);
        }

        if (MyStringUtil.equals(yearStr.trim(), Calendar.getInstance().get(Calendar.YEAR) + "")) {
            tv_time.setText(MyStringUtil.getTimeStr(System.currentTimeMillis(), MyStringUtil.TIME_FORMAT_ONE));
        } else {
            tv_time.setText(yearStr.trim() + "-01-01");
        }
        tv_order.setSelected(true);
    }

    public void oClick(View v) {
        switch (v.getId()) {
            case R.id.ll_order:
                if (!list_cacc.isEmpty()) {
                    MySelectedDialogFragment.newInstance(R.layout.select_dialog_ll, list_cacc, new MySelectedDialogFragment.SureListener() {
                        @Override
                        public void sure(String str) {
                            if (!MyStringUtil.equals(caccStr.trim(), str.trim())) {
                                caccStr = str;
                                changeSlected(false);
                            }
                        }
                    }).show(getSupportFragmentManager(), "");
                }
                break;
            case R.id.ll_year:
                if (!years.isEmpty()) {
                    MySelectedDialogFragment.newInstance(R.layout.select_dialog_2_ll, years, new MySelectedDialogFragment.SureListener() {
                        @Override
                        public void sure(String str) {
                            if (!MyStringUtil.equals(yearStr.trim(), str.trim())) {
                                yearStr = str;
                                tv_year.setText(yearStr);
                                tv_time.setText(yearStr + "-01-01");
                            }
                        }
                    }).show(getSupportFragmentManager(), "");
                }
                break;
            case R.id.ll_time:
                if (!MyStringUtil.isEmpty(yearStr) && yearStr.matches("^[0-9]*$")) {
                    MySelectedDialogFragmentTime.newInstance(yearStr, new MySelectedDialogFragmentTime.SureListener() {
                        @Override
                        public void sure(String str) {
                            tv_time.setText(str);
                        }
                    }).show(getSupportFragmentManager(), "");
                }
                break;
            case R.id.tv_ok:
                login_choose();
                break;
        }
    }


    private void changeSlected(boolean isFirst) {
        if (!isFirst) {
            tv_order.setText(caccStr);
            int index = list_cacc.indexOf(caccStr.trim());
            caccIdStr = list_id.get(index);
            years.clear();
            years.addAll(Arrays.asList(list_iyear.get(index).split(",")));
            yearStr = years.get(0);
            tv_year.setText(yearStr);
            tv_time.setText(yearStr + "-01-01");
            return;
        }

        if (list_cacc.size() == 0 || list_id.size() == 0 || list_iyear.size() == 0) return;
        if (list_cacc.contains(caccStr.trim())) {
            int index = list_cacc.indexOf(caccStr.trim());
            caccIdStr = list_id.get(index);
            years.addAll(Arrays.asList(list_iyear.get(index).split(",")));
            if (!years.contains(yearStr.trim())) {
                yearStr = years.get(0);
                tv_year.setText(yearStr);
                tv_time.setText(yearStr + "-01-01");
            }
        } else {
            caccStr = list_cacc.get(0);
            caccIdStr = list_id.get(0);
            years.addAll(Arrays.asList(list_iyear.get(0).split(",")));
            yearStr = years.get(0);
            tv_order.setText(caccStr);
            tv_year.setText(yearStr);
            tv_time.setText(yearStr + "-01-01");
        }
    }

    public void deviceCheck(final String regId) {
        String name = SpUtil.getString(Login_choose.this, ConstanceHeTai.user_name);
        String murl = SpUtil.getString(Login_choose.this, ConstanceHeTai.login_server_address);
        String url=ConstanceHttp.base_url+murl+ConstanceHttp.sysabout_Login_Check;
        OkHttpUtils.post().addParams("username", name).addParams("devicetype", "android").addParams("registrationId",regId ).url(url).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                ToastUtil.showToast("服务器异常");
            }

            @Override
            public void onResponse(String response, int id) {
                try {
                    if (TextUtils.isEmpty(response)){
                        ToastUtil.showToast("数据异常");
                    }else {
                        JSONObject jsonObject=new JSONObject(response);
                        int num = jsonObject.getInt("num");//当返回为1是，按钮显示为登录，允许点击；
                      //  为-1时显示为未审核，不允许点击；-2显示为“失效”，不允许点击。
                        if (num==1){
                            tv_ok.setText("登陆");
                            tv_ok.setEnabled(true);
                        }else if (num==-1){
                            tv_ok.setText("未审核");
                            tv_ok.setEnabled(false);
                        }else {
                            tv_ok.setText("失效");
                            tv_ok.setEnabled(false);
                        }

                    }
                }catch (Exception ex){
                    ex.printStackTrace();
                }



            }
        });
    }


    //确定登录
    private void login_choose() {
        if (MyStringUtil.isEmpty(caccStr) || MyStringUtil.isEmpty(yearStr)) {
            new AlertDialog.Builder(Login_choose.this)
                    .setTitle(R.string.loginerror)
                    .setMessage("账套或者年度不能为空，\n请选择后再登录！")
                    .create().show();
            return;
        }

        //登录成功记录默认账套和年度
        String gd_sj = tv_time.getText().toString();
        SharedPreferences.Editor editor = application.mSharedPreferences.edit();
        editor.putString("cacc_id", caccIdStr);
        editor.putString("cacc_name", caccStr);
        editor.putString("ciyear", yearStr);
        editor.putString("gd_sj", gd_sj);
        editor.commit();
        //记录全局变量
        application.setGs_ztid(caccIdStr);
        application.setGs_ztname(caccStr);
        application.setGs_year(yearStr);
        application.setGs_sj(gd_sj);
        getUaAccount(caccIdStr, editor);

        Intent intent = new Intent();

        intent.putExtra("regId1", regId1);
        intent.putExtra("caccIdStr", caccIdStr);
        intent.putExtra("yearStr", yearStr);

        intent.setClass(Login_choose.this, MainActivity.class);
        startActivity(intent);
    }

    public void getUaAccount(String cacc_id, final SharedPreferences.Editor editor) {
        String nameSpace = "http://service.test.com";
        String methodName = "getUaAccount";
        String urlString = "http://" + InstorageURL.SERVERURL + BaseUrl_New;
        AbSoapParams params = new AbSoapParams();
        params.put("arg0", cacc_id);
        mAbSoapUtil.call(urlString, nameSpace, methodName, params, new AbSoapListener() {
            //获取数据成功会调用这里
            @Override
            public void onSuccess(int statusCode, String content) {
                if (content != null) {
                    uaaccountlist = new ArrayList<UaAccount>();
                    UaAccount info = new UaAccount();
                    String str = content.split("UaAccount=anyType")[1].trim().replace(" ", "").replace("anyType{}", "null");
                    str = str.replace(";};};}", "\"}").replace("=", "\":\"").replace(";", "\",\"").replace("{", "{\"");
                    try {
                        JSONObject dataJson = new JSONObject(str);
                        info.setcAcc_Id(string2null(dataJson.getString("cAcc_Id")));
                        info.setcAcc_Name(string2null(dataJson.getString("cAcc_Name")));
                        info.setcUnitAbbre(string2null(dataJson.getString("cUnitAbbre")));
                        info.setcUnitAddr(string2null(dataJson.getString("cUnitAddr")));
                        info.setcUnitEMail(string2null(dataJson.getString("cUnitEMail")));
                        info.setcUnitFax(string2null(dataJson.getString("cUnitFax")));
                        info.setcUnitLP(string2null(dataJson.getString("cUnitLP")));
                        info.setcUnitName(string2null(dataJson.getString("cUnitName")));
                        info.setcUnitTaxNo(string2null(dataJson.getString("cUnitTaxNo")));
                        info.setcUnitTel(string2null(dataJson.getString("cUnitTel")));
                        info.setcUnitZap(string2null(dataJson.getString("cUnitZap")));
                        info.setZcode(string2null(dataJson.getString("zcode")));
                        uaaccountlist.add(info);
                        //记录到全局变量中
                        if (uaaccountlist != null && uaaccountlist.size() > 0) {
                            editor.putString("cAcc_Id", uaaccountlist.get(0).getcAcc_Id());
                            editor.putString("cAcc_Name", uaaccountlist.get(0).getcAcc_Name());
                            editor.putString("cUnitAbbre", uaaccountlist.get(0).getcUnitAbbre());
                            editor.putString("cUnitAddr", uaaccountlist.get(0).getcUnitAddr());
                            editor.putString("cUnitEMail", uaaccountlist.get(0).getcUnitEMail());
                            editor.putString("cUnitFax", uaaccountlist.get(0).getcUnitFax());
                            editor.putString("cUnitLP", uaaccountlist.get(0).getcUnitLP());
                            editor.putString("cUnitName", uaaccountlist.get(0).getcUnitName());
                            editor.putString("cUnitTaxNo", uaaccountlist.get(0).getcUnitTaxNo());
                            editor.putString("cUnitTel", uaaccountlist.get(0).getcUnitTel());
                            editor.putString("cUnitZap", uaaccountlist.get(0).getcUnitZap());
                            editor.putString("zcode", uaaccountlist.get(0).getZcode());
                            editor.commit();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    AbToastUtil.showToast(Login_choose.this, R.string.sqlerrormsg);
                }
            }

            // 失败，调用
            @Override
            public void onFailure(int statusCode, String content,
                                  Throwable error) {
                AbToastUtil.showToast(Login_choose.this, R.string.toast_server_error);
            }

            @Override
            public void onStart() {
            }

            @Override
            public void onFinish() {
            }
        });
    }

    //手机上的返回按钮
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            this.finish();
        }
        return false;
    }
}
